
import jwt from 'jsonwebtoken'

import bcrypt from 'bcryptjs'
const SALT_ROUNDS = 12
const JWT_SECRET = process.env.JWT_SECRET || 'your-fallback-secret'

// 密码加密
export const hashPassword = async (password: string): Promise<string> => {
  return await bcrypt.hash(password, SALT_ROUNDS)
}

// 密码验证
export const verifyPassword = async (password: string, hashedPassword: string): Promise<boolean> => {
  return await bcrypt.compare(password, hashedPassword)
}

// JWT令牌签发
export const signToken = (userId: number, username: string): string => {
  return jwt.sign(
    { userId, username },
    JWT_SECRET,
    { expiresIn: '24h' }
  )
}

// JWT令牌验证
export const verifyToken = (token: string): any => {
  try {
    return jwt.verify(token, JWT_SECRET)
  } catch (error) {
    return null
  }
}